package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.product.domain.ProductAssociation;
import cn.ibizlab.businesscentral.core.product.service.IProductAssociationService;
import cn.ibizlab.businesscentral.core.product.filter.ProductAssociationSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"产品关联" })
@RestController("CentralApi-productassociation")
@RequestMapping("")
public class ProductAssociationResource {

    @Autowired
    public IProductAssociationService productassociationService;

    @Autowired
    @Lazy
    public ProductAssociationMapping productassociationMapping;

    @PreAuthorize("hasPermission(this.productassociationMapping.toDomain(#productassociationdto),'iBizBusinessCentral-ProductAssociation-Create')")
    @ApiOperation(value = "新建产品关联", tags = {"产品关联" },  notes = "新建产品关联")
	@RequestMapping(method = RequestMethod.POST, value = "/productassociations")
    public ResponseEntity<ProductAssociationDTO> create(@RequestBody ProductAssociationDTO productassociationdto) {
        ProductAssociation domain = productassociationMapping.toDomain(productassociationdto);
		productassociationService.create(domain);
        ProductAssociationDTO dto = productassociationMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.productassociationMapping.toDomain(#productassociationdtos),'iBizBusinessCentral-ProductAssociation-Create')")
    @ApiOperation(value = "批量新建产品关联", tags = {"产品关联" },  notes = "批量新建产品关联")
	@RequestMapping(method = RequestMethod.POST, value = "/productassociations/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<ProductAssociationDTO> productassociationdtos) {
        productassociationService.createBatch(productassociationMapping.toDomain(productassociationdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "productassociation" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.productassociationService.get(#productassociation_id),'iBizBusinessCentral-ProductAssociation-Update')")
    @ApiOperation(value = "更新产品关联", tags = {"产品关联" },  notes = "更新产品关联")
	@RequestMapping(method = RequestMethod.PUT, value = "/productassociations/{productassociation_id}")
    public ResponseEntity<ProductAssociationDTO> update(@PathVariable("productassociation_id") String productassociation_id, @RequestBody ProductAssociationDTO productassociationdto) {
		ProductAssociation domain  = productassociationMapping.toDomain(productassociationdto);
        domain .setProductassociationid(productassociation_id);
		productassociationService.update(domain );
		ProductAssociationDTO dto = productassociationMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.productassociationService.getProductassociationByEntities(this.productassociationMapping.toDomain(#productassociationdtos)),'iBizBusinessCentral-ProductAssociation-Update')")
    @ApiOperation(value = "批量更新产品关联", tags = {"产品关联" },  notes = "批量更新产品关联")
	@RequestMapping(method = RequestMethod.PUT, value = "/productassociations/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<ProductAssociationDTO> productassociationdtos) {
        productassociationService.updateBatch(productassociationMapping.toDomain(productassociationdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.productassociationService.get(#productassociation_id),'iBizBusinessCentral-ProductAssociation-Remove')")
    @ApiOperation(value = "删除产品关联", tags = {"产品关联" },  notes = "删除产品关联")
	@RequestMapping(method = RequestMethod.DELETE, value = "/productassociations/{productassociation_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("productassociation_id") String productassociation_id) {
         return ResponseEntity.status(HttpStatus.OK).body(productassociationService.remove(productassociation_id));
    }

    @PreAuthorize("hasPermission(this.productassociationService.getProductassociationByIds(#ids),'iBizBusinessCentral-ProductAssociation-Remove')")
    @ApiOperation(value = "批量删除产品关联", tags = {"产品关联" },  notes = "批量删除产品关联")
	@RequestMapping(method = RequestMethod.DELETE, value = "/productassociations/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        productassociationService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.productassociationMapping.toDomain(returnObject.body),'iBizBusinessCentral-ProductAssociation-Get')")
    @ApiOperation(value = "获取产品关联", tags = {"产品关联" },  notes = "获取产品关联")
	@RequestMapping(method = RequestMethod.GET, value = "/productassociations/{productassociation_id}")
    public ResponseEntity<ProductAssociationDTO> get(@PathVariable("productassociation_id") String productassociation_id) {
        ProductAssociation domain = productassociationService.get(productassociation_id);
        ProductAssociationDTO dto = productassociationMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取产品关联草稿", tags = {"产品关联" },  notes = "获取产品关联草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/productassociations/getdraft")
    public ResponseEntity<ProductAssociationDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(productassociationMapping.toDto(productassociationService.getDraft(new ProductAssociation())));
    }

    @ApiOperation(value = "检查产品关联", tags = {"产品关联" },  notes = "检查产品关联")
	@RequestMapping(method = RequestMethod.POST, value = "/productassociations/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody ProductAssociationDTO productassociationdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(productassociationService.checkKey(productassociationMapping.toDomain(productassociationdto)));
    }

    @PreAuthorize("hasPermission(this.productassociationMapping.toDomain(#productassociationdto),'iBizBusinessCentral-ProductAssociation-Save')")
    @ApiOperation(value = "保存产品关联", tags = {"产品关联" },  notes = "保存产品关联")
	@RequestMapping(method = RequestMethod.POST, value = "/productassociations/save")
    public ResponseEntity<Boolean> save(@RequestBody ProductAssociationDTO productassociationdto) {
        return ResponseEntity.status(HttpStatus.OK).body(productassociationService.save(productassociationMapping.toDomain(productassociationdto)));
    }

    @PreAuthorize("hasPermission(this.productassociationMapping.toDomain(#productassociationdtos),'iBizBusinessCentral-ProductAssociation-Save')")
    @ApiOperation(value = "批量保存产品关联", tags = {"产品关联" },  notes = "批量保存产品关联")
	@RequestMapping(method = RequestMethod.POST, value = "/productassociations/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<ProductAssociationDTO> productassociationdtos) {
        productassociationService.saveBatch(productassociationMapping.toDomain(productassociationdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-ProductAssociation-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-ProductAssociation-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"产品关联" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/productassociations/fetchdefault")
	public ResponseEntity<List<ProductAssociationDTO>> fetchDefault(ProductAssociationSearchContext context) {
        Page<ProductAssociation> domains = productassociationService.searchDefault(context) ;
        List<ProductAssociationDTO> list = productassociationMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-ProductAssociation-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-ProductAssociation-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"产品关联" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/productassociations/searchdefault")
	public ResponseEntity<Page<ProductAssociationDTO>> searchDefault(@RequestBody ProductAssociationSearchContext context) {
        Page<ProductAssociation> domains = productassociationService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(productassociationMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasPermission(this.productassociationMapping.toDomain(#productassociationdto),'iBizBusinessCentral-ProductAssociation-Create')")
    @ApiOperation(value = "根据产品建立产品关联", tags = {"产品关联" },  notes = "根据产品建立产品关联")
	@RequestMapping(method = RequestMethod.POST, value = "/products/{product_id}/productassociations")
    public ResponseEntity<ProductAssociationDTO> createByProduct(@PathVariable("product_id") String product_id, @RequestBody ProductAssociationDTO productassociationdto) {
        ProductAssociation domain = productassociationMapping.toDomain(productassociationdto);
        domain.setProductid(product_id);
		productassociationService.create(domain);
        ProductAssociationDTO dto = productassociationMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.productassociationMapping.toDomain(#productassociationdtos),'iBizBusinessCentral-ProductAssociation-Create')")
    @ApiOperation(value = "根据产品批量建立产品关联", tags = {"产品关联" },  notes = "根据产品批量建立产品关联")
	@RequestMapping(method = RequestMethod.POST, value = "/products/{product_id}/productassociations/batch")
    public ResponseEntity<Boolean> createBatchByProduct(@PathVariable("product_id") String product_id, @RequestBody List<ProductAssociationDTO> productassociationdtos) {
        List<ProductAssociation> domainlist=productassociationMapping.toDomain(productassociationdtos);
        for(ProductAssociation domain:domainlist){
            domain.setProductid(product_id);
        }
        productassociationService.createBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "productassociation" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.productassociationService.get(#productassociation_id),'iBizBusinessCentral-ProductAssociation-Update')")
    @ApiOperation(value = "根据产品更新产品关联", tags = {"产品关联" },  notes = "根据产品更新产品关联")
	@RequestMapping(method = RequestMethod.PUT, value = "/products/{product_id}/productassociations/{productassociation_id}")
    public ResponseEntity<ProductAssociationDTO> updateByProduct(@PathVariable("product_id") String product_id, @PathVariable("productassociation_id") String productassociation_id, @RequestBody ProductAssociationDTO productassociationdto) {
        ProductAssociation domain = productassociationMapping.toDomain(productassociationdto);
        domain.setProductid(product_id);
        domain.setProductassociationid(productassociation_id);
		productassociationService.update(domain);
        ProductAssociationDTO dto = productassociationMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.productassociationService.getProductassociationByEntities(this.productassociationMapping.toDomain(#productassociationdtos)),'iBizBusinessCentral-ProductAssociation-Update')")
    @ApiOperation(value = "根据产品批量更新产品关联", tags = {"产品关联" },  notes = "根据产品批量更新产品关联")
	@RequestMapping(method = RequestMethod.PUT, value = "/products/{product_id}/productassociations/batch")
    public ResponseEntity<Boolean> updateBatchByProduct(@PathVariable("product_id") String product_id, @RequestBody List<ProductAssociationDTO> productassociationdtos) {
        List<ProductAssociation> domainlist=productassociationMapping.toDomain(productassociationdtos);
        for(ProductAssociation domain:domainlist){
            domain.setProductid(product_id);
        }
        productassociationService.updateBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.productassociationService.get(#productassociation_id),'iBizBusinessCentral-ProductAssociation-Remove')")
    @ApiOperation(value = "根据产品删除产品关联", tags = {"产品关联" },  notes = "根据产品删除产品关联")
	@RequestMapping(method = RequestMethod.DELETE, value = "/products/{product_id}/productassociations/{productassociation_id}")
    public ResponseEntity<Boolean> removeByProduct(@PathVariable("product_id") String product_id, @PathVariable("productassociation_id") String productassociation_id) {
		return ResponseEntity.status(HttpStatus.OK).body(productassociationService.remove(productassociation_id));
    }

    @PreAuthorize("hasPermission(this.productassociationService.getProductassociationByIds(#ids),'iBizBusinessCentral-ProductAssociation-Remove')")
    @ApiOperation(value = "根据产品批量删除产品关联", tags = {"产品关联" },  notes = "根据产品批量删除产品关联")
	@RequestMapping(method = RequestMethod.DELETE, value = "/products/{product_id}/productassociations/batch")
    public ResponseEntity<Boolean> removeBatchByProduct(@RequestBody List<String> ids) {
        productassociationService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.productassociationMapping.toDomain(returnObject.body),'iBizBusinessCentral-ProductAssociation-Get')")
    @ApiOperation(value = "根据产品获取产品关联", tags = {"产品关联" },  notes = "根据产品获取产品关联")
	@RequestMapping(method = RequestMethod.GET, value = "/products/{product_id}/productassociations/{productassociation_id}")
    public ResponseEntity<ProductAssociationDTO> getByProduct(@PathVariable("product_id") String product_id, @PathVariable("productassociation_id") String productassociation_id) {
        ProductAssociation domain = productassociationService.get(productassociation_id);
        ProductAssociationDTO dto = productassociationMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "根据产品获取产品关联草稿", tags = {"产品关联" },  notes = "根据产品获取产品关联草稿")
    @RequestMapping(method = RequestMethod.GET, value = "/products/{product_id}/productassociations/getdraft")
    public ResponseEntity<ProductAssociationDTO> getDraftByProduct(@PathVariable("product_id") String product_id) {
        ProductAssociation domain = new ProductAssociation();
        domain.setProductid(product_id);
        return ResponseEntity.status(HttpStatus.OK).body(productassociationMapping.toDto(productassociationService.getDraft(domain)));
    }

    @ApiOperation(value = "根据产品检查产品关联", tags = {"产品关联" },  notes = "根据产品检查产品关联")
	@RequestMapping(method = RequestMethod.POST, value = "/products/{product_id}/productassociations/checkkey")
    public ResponseEntity<Boolean> checkKeyByProduct(@PathVariable("product_id") String product_id, @RequestBody ProductAssociationDTO productassociationdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(productassociationService.checkKey(productassociationMapping.toDomain(productassociationdto)));
    }

    @PreAuthorize("hasPermission(this.productassociationMapping.toDomain(#productassociationdto),'iBizBusinessCentral-ProductAssociation-Save')")
    @ApiOperation(value = "根据产品保存产品关联", tags = {"产品关联" },  notes = "根据产品保存产品关联")
	@RequestMapping(method = RequestMethod.POST, value = "/products/{product_id}/productassociations/save")
    public ResponseEntity<Boolean> saveByProduct(@PathVariable("product_id") String product_id, @RequestBody ProductAssociationDTO productassociationdto) {
        ProductAssociation domain = productassociationMapping.toDomain(productassociationdto);
        domain.setProductid(product_id);
        return ResponseEntity.status(HttpStatus.OK).body(productassociationService.save(domain));
    }

    @PreAuthorize("hasPermission(this.productassociationMapping.toDomain(#productassociationdtos),'iBizBusinessCentral-ProductAssociation-Save')")
    @ApiOperation(value = "根据产品批量保存产品关联", tags = {"产品关联" },  notes = "根据产品批量保存产品关联")
	@RequestMapping(method = RequestMethod.POST, value = "/products/{product_id}/productassociations/savebatch")
    public ResponseEntity<Boolean> saveBatchByProduct(@PathVariable("product_id") String product_id, @RequestBody List<ProductAssociationDTO> productassociationdtos) {
        List<ProductAssociation> domainlist=productassociationMapping.toDomain(productassociationdtos);
        for(ProductAssociation domain:domainlist){
             domain.setProductid(product_id);
        }
        productassociationService.saveBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-ProductAssociation-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-ProductAssociation-Get')")
	@ApiOperation(value = "根据产品获取DEFAULT", tags = {"产品关联" } ,notes = "根据产品获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/products/{product_id}/productassociations/fetchdefault")
	public ResponseEntity<List<ProductAssociationDTO>> fetchProductAssociationDefaultByProduct(@PathVariable("product_id") String product_id,ProductAssociationSearchContext context) {
        context.setN_productid_eq(product_id);
        Page<ProductAssociation> domains = productassociationService.searchDefault(context) ;
        List<ProductAssociationDTO> list = productassociationMapping.toDto(domains.getContent());
	    return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-ProductAssociation-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-ProductAssociation-Get')")
	@ApiOperation(value = "根据产品查询DEFAULT", tags = {"产品关联" } ,notes = "根据产品查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/products/{product_id}/productassociations/searchdefault")
	public ResponseEntity<Page<ProductAssociationDTO>> searchProductAssociationDefaultByProduct(@PathVariable("product_id") String product_id, @RequestBody ProductAssociationSearchContext context) {
        context.setN_productid_eq(product_id);
        Page<ProductAssociation> domains = productassociationService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(productassociationMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

